{% extends 'base.html.twig' %}

{% block stylesheets %}
<style>
    #body {
        background: transparent url('{{ imgsrc("images/bg2.jpg") }}') no-repeat top center;
        background-size: cover;
    }
    .top { position: absolute; top: 0px; width: 100%; z-index: 10; }
    .top img { width: 100%; }
    .boardwrapper { position: absolute; width: 100%; top: 10px; }
    .board {
        position: relative; width: 205px; height: 65px; margin: 0 auto;
        background: transparent url('{{ imgsrc("images/board.png") }}') no-repeat top center;
        background-size: cover;
    }
    .board img { width: 100%; }
    .cd { position: absolute; top: 38px; left: 6px; width: 58px; text-align: center; color: #FFF7C3; font-size: 18px; font-weight: bold; }
    .score { position: absolute; top: 38px; left: 72px; width: 128px; text-align: center; color: #FFF7C3; font-size: 18px; font-weight: bold; }
    .score:before {  content: "得分:";}
    .bubble-hint {
        position: absolute; width: 100%; text-align: center; top: 240px; left: 0px; opacity: 0;
        color: #FFF7C3; font-weight: bold; font-size: 24px; text-shadow: 2px 2px #000000;
    }
    .loading {
        position: absolute; width: 100%; text-align: center; top: 240px;
        color: #FFF7C3; font-weight: bold; font-size: 22px; text-shadow: 2px 2px #000000;
    }
    #stage { display: block; margin: 0 auto; width: 320px; }
    .overlay { display: block; }
    .overlay .rule { width: 100%; }
    .overlay .btnstart { display: block; width: 122px; margin: 5px auto; }
    .overlay .btnstart img { width: 100%; }
    #sfx-bgm { display: none; }
</style>
{% endblock %}

{% block body %}
    <div class='top'><img src='{{ imgsrc("images/top.png") }}' /></div>
    <div class='boardwrapper'>
        <div class='board'>
            <div class='cd'>00:<span class='cdtime'>30</span></div>
            <div class='score'>0</div>
        </div>
    </div>
    
    <div class='bubble-hint'>+1</div>
    <div class='loading'>加载中...</div>
    <canvas id="stage" width="320" height="460"></canvas>
    <div class='overlay'>
        <img class='rule' src='{{ imgsrc("images/rules.png") }}?v=10'>
        <a class='btnstart' href='#'><img src='{{ imgsrc("images/btnstart.png") }}'></a>
    </div>
    <audio id="sfx-bgm" preload="auto" loop="loop">
        <source src='{{ imgsrc("audio/bgm.lite.mp3") }}?v=2' type="audio/mpeg">
    </audio>
{% endblock %}
    
{% block javascripts %}
{{ js('js/underscore-min.js') }}
{{ js('js/easeljs-0.8.0.min.js') }}
{{ js('js/preloadjs-0.6.0.min.js') }}
{{ js('js/TweenMax.min.js') }}
{{ js('js/TimelineMax.min.js') }}
<script>
function pad(value, length) {
    return (value.toString().length < length) ? pad("0"+value, length):value;
}
$(function(){
    $('#body, #stage').css('height', h);
    $('#stage').attr('width', w).attr('height', h).css({
        width: w,
        height: h
    });
    
    $('.btnstart').click( function(e){
        e.preventDefault();
        preload.on("complete", handleComplete);
        preload.loadManifest([{src:'{{ imgsrc("images/spritesheet.png") }}', id:"spritesheet"}]);
        TweenMax.to($('.overlay'), 0.5, { opacity: 0, display: 'none' });
        document.getElementById('sfx-bgm').play();
        // $('.overlay').velocity('fadeOut');
    });
    
    var hints = [
        '金币+1',
        '-5秒',
        '名家之约x3',
        '健康管理x3',
        '客服节x3',
        '全国通+5秒',
        '立保通+5秒'
    ];
    var effects = [
        [1, 0],
        [0, -5],
        ['x3', 0],
        ['x3', 0],
        ['x3', 0],
        [0, 5],
        [0, 5]
    ];
    var spriteSheetFrames = [
        // x, y, width, height, imageIndex, regX, regY
        [385,243, 44,37, 0, 0,0], 	//coin
        [0,398, 52,55, 0, 0,0], 	//bomb
        [57,344, 56,53, 0, 0,0], 	//b1
        [96,294, 53,50, 0, 0,0], 	//b2
        [202,294, 53,49, 0, 0,0], 	//b3
        [0,344, 57,54, 0, 0,0], 	//b4
        [149,294, 53,49, 0, 0,0], 	//b5
        [194,243, 97,49, 0, 0,0], 	//font1
        [97,243, 97,49, 0, 0,0], 	//font2
        [0,294, 96,50, 0, 0,0], 	//font3
        [0,243, 97,51, 0, 0,0], 	//font4
        [291,243, 94,47, 0, 0,0], 	//font5
        [303,0, 260,240, 0, 0,0], 	//character
        [0,0, 303,243, 0, 0,0] 	//explode
    ];
    
    var kStageLeftEdge  = 40;
    var kStageRightEdge = w - 40;
    var kStageBottomEdge = h; // fall to
    var kFallingBottomLine = h - 90;
    var kCharacterY = h < 470 ? h - 80 : h - 140;
    
    var fallingSprites = [];
    var character;
    
    var onTick = function(e) {
        stage.update(e);
        
        _.each(fallingSprites, function(fallingSprite) {
            if (fallingSprite.y > kFallingBottomLine) {
                fallingSprite.destroyed = 1;
                stage.removeChild(fallingSprite);
                return;
            }
            if (fallingSprite.destroyed || fallingSprite.y < kCharacterY - 100) {
                return;
            }
            
            if (fallingSprite.x > character.x - 10 && fallingSprite.x < character.x + 110) {
                /*
                var bubbleHint = $('<div class="bubble-hint"></div>');
                $('#body').append(bubbleHint);
                bubbleHint.text(fallingSprite.hint);
                */
                if (fallingSprite.hint) {
                    TweenMax.fromTo(
                        fallingSprite.hint,
                        2.6,
                        { y: 470, alpha: 1 },
                        { y: -100, alpha: 0
                        }
                    );
                }
                
                fallingSprite.destroyed = 1;
                stage.removeChild(fallingSprite);
                if (fallingSprite.currentFrame === 1) {
                    var explode = character.getChildByName('explode');
                    explode.alpha = 1;
                    TweenMax.to(explode, 0.1, { alpha:0, delay:0.2 });
                }
                
                if (fallingSprite.scoreEffect) {
                    var currentScore = parseInt($('.score').text());
                    var score = currentScore;
                    var scoreEffect = fallingSprite.scoreEffect;
                    if (_.isString(scoreEffect)) {
                        if (scoreEffect.substring(0, 1) === 'x') {
                            if (score === 0) {
                                score = 1;
                            }

                            score *= parseInt(scoreEffect.substring(1));
                        }
                    } else {
                        score += scoreEffect;
                    }
                    $('.score').text(score);
                }
                
                if (fallingSprite.timeEffect) {
                    var timeEffect = fallingSprite.timeEffect;
                    var currentTime = parseInt($('.cdtime').text());
                    $('.cdtime').text(pad(_.max([0, currentTime + timeEffect]), 2));
                }
            }
        });
    }; // end of onTick
    
    var cdTimer;
    
    var gameover = function() {
        window.clearInterval(cdTimer);
        window.clearInterval(spawnTimer);
        TweenMax.killAll();
        $('.bubble-hint').remove();
        
        _.each(fallingSprites, function(sprite){
            stage.removeChild(sprite);
        });
        var score = $('.score').text();
        $.ajax({
            url: '{{ urlFor('submit') }}',
            type: 'POST',
            data: {
                score: score,
                submit: 1
            },
            success: function(rsp){
                // window.location.href = '{{ urlFor("result") }}';
            }
        });
    };
    
    var stage = new createjs.Stage('stage');
    stage.interactionEnabled = false;
    createjs.Ticker.setFPS(60);
    createjs.Ticker.addEventListener("tick", onTick);
    createjs.Touch.enable(stage);
    
    var textShadow = new createjs.Shadow("#333333", 2, 2, 0);
    var hintSprites = [];
    _.each(hints, function(hint){
        var bubbleHint = new createjs.Text(hint, "bold 48px 黑体", "#FFF7C3");
        var hintw = Math.round(bubbleHint.getBounds().width);
        bubbleHint.regX = 0;
        bubbleHint.x = w - hintw/2;
        bubbleHint.y = -100;
        bubbleHint.shadow = textShadow;
        //bubbleHint.cache(0, 0, hintw, bubbleHint.getBounds().height);
        stage.addChild(bubbleHint);
        hintSprites.push(bubbleHint);
    });
        
    if (window.devicePixelRatio > 1) {
        
        kStageRightEdge *= window.devicePixelRatio;
        kStageBottomEdge *= window.devicePixelRatio;
        kFallingBottomLine *= window.devicePixelRatio;
        kCharacterY *= window.devicePixelRatio;
        
        // grab the width and height from canvas
        var canvas = document.getElementById('stage');
        var height = canvas.getAttribute('height');
        var width = canvas.getAttribute('width');
        
        // reset the canvas width and height with window.devicePixelRatio applied
        canvas.setAttribute('width', Math.round(width * window.devicePixelRatio));
        canvas.setAttribute('height', Math.round( height * window.devicePixelRatio));
        // force the canvas back to the original size using css
        canvas.style.width = width + "px";
        canvas.style.height = height + "px";
    } else if (window.devicePixelRatio === 1) {
        stage.scaleX = stage.scaleY = 0.5;
        
        kStageBottomEdge *= 2;
        kFallingBottomLine *= 2;
        kCharacterY *= 2;
    }
    
    var spawnTimer;
    var preload = new createjs.LoadQueue();
    var handleComplete = function() {
        TweenMax.to($('.loading'), 0.8, { opacity: 0, top: '-=80' });
        var spritesheet = new createjs.SpriteSheet({
            images: [preload.getResult("spritesheet")],
            frames: spriteSheetFrames
        });
        
        var fallingGenerator = {
            spawn: function (type){
                // type 0..11
                
                var fallingSprite = new createjs.Sprite(spritesheet, type);
                fallingSprite.tickEnabled = false;
                // 金币、炸弹、红球、绿球、蓝球、黄球、紫球
                if (hintSprites[type]) {
                    fallingSprite.hint = hintSprites[type];
                }
                if (effects[type]) {
                    fallingSprite.scoreEffect = effects[type][0];
                    fallingSprite.timeEffect  = effects[type][1];
                }
                //fallingSprite.graphics.beginFill(colors[type]);
                fallingSprite.regX = 10;
                fallingSprite.regY = 10;
                //fallingSprite.scaleX = fallingSprite.scaleY = 0.5;
                fallingSprite.x = _.random(100, kStageRightEdge*(1/stage.scaleX));
                fallingSprite.y = -20;
                //fallingSprite.graphics.drawCircle(10, 10, 10);
                fallingSprites.push(fallingSprite);

                stage.addChild(fallingSprite);
                var duration = _.random(18, 40)/10;
                TweenMax.to(fallingSprite, duration, { y: kStageBottomEdge });
            }
        };
        
        // 产生掉落
        var sprites = [];
        // 80个金币
        _.times(80, function(){
            sprites.push(0);
        });
        // 20个炸弹
        _.times(12, function(){
            sprites.push(1);
        });
        _.times(4, function(){
            sprites.push(2);
            sprites.push(3);
        });
        // 各种球
        _.times(3, function(){
            sprites.push(4);
            sprites.push(5);
            sprites.push(6);
        });
        // 文字
        _.times(3, function(){
            sprites.push(7);
            sprites.push(8);
            sprites.push(9);
            sprites.push(10);
            sprites.push(11);
        });
        sprites = _.shuffle(sprites);
        // 100多个掉落游戏应该已结束
        _.times(200, function(){
            sprites.push(0);
        });
        
        var index = 0;
        spawnTimer = setInterval(function(){
            fallingGenerator.spawn(sprites[index]);
            fallingGenerator.spawn(0);
            ++index;
            fallingSprites = _.filter(fallingSprites, function(sprite){
                return sprite.destroyed !== 1;
            });
        }, 600);
        
        var sheep = new createjs.Sprite(spritesheet, 12);
        var explode = new createjs.Sprite(spritesheet, 13);
        
        character = new createjs.Container();
        explode.x = 60;
        explode.y = -96;
        explode.alpha = 0;
        explode.name = 'explode';
        character.addChild(sheep, explode);
        
        character.regX = 115;
        character.regY = 108;
        character.x = 115;
        character.y = kCharacterY;
        character.tickEnabled = false;
        stage.addChild(character);
        
        character.on('pressmove', function(e) {
            if (e.stageX < kStageLeftEdge || e.stageX > kStageRightEdge) {
                return;
            }
            character.x = e.stageX*(1/stage.scaleX);
        });
        
        // game start
        cdTimer = window.setInterval(function(){
            var cd = parseInt($('.cdtime').text());
            if (cd === 0) {
                gameover();
                return;
            }
            $('.cdtime').text(pad(cd - 1, 2));
        }, 1000);
    }; // handleComplete
 });
</script>
{% endblock %}